package com.mvpandroiddemo.register;


import com.mvpandroiddemo.net.APIHelper;
import com.mvpandroiddemo.utils.Constance;
import com.mvpandroiddemo.utils.SharedPreferenceHelper;
import com.orhanobut.logger.Logger;


import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * @Description $description$
 * @Author owner
 * @CreateTime 2019/10/15 14:32
 **/
public class RegisterModel implements RegisterControl.IRegisterModel {

    private RegisterPresent registerPresent;

    public RegisterModel(RegisterPresent registerPresent) {
        this.registerPresent = registerPresent;
    }

    @Override
    public void onRegister(String userName, String pwd, String repwd, OnRegisterListener onRegisterListener) {

        Disposable disposable = APIHelper.getInstance()
                .getNetServices()
                .registerAccount(userName, pwd, repwd)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(baseBean -> {
                            Logger.d("获取到具体=> " + baseBean.toString());
                            int errorCode = baseBean.getErrorCode();
                            if (errorCode == Constance.Net_Tag_failure) {
                                onRegisterListener.onRegisterFailed(baseBean.getErrorMsg());
                            } else {
                                RegisterBean beanData = baseBean.getData();
                                String name = beanData.getUsername();
                                String password = beanData.getPassword();
                                SharedPreferenceHelper preferenceHelper = SharedPreferenceHelper.getInstance();
                                preferenceHelper.saveData(Constance.Cache_user_name, name);
                                preferenceHelper.saveData(Constance.Cache_user_pwd, password);
                                APIHelper.getInstance().init();
                                onRegisterListener.onRegisterSuccess(beanData);
                            }
                        },
                        throwable -> {
                            Logger.d("出现错误 => " + throwable.getMessage());
                            onRegisterListener.onRegisterFailed("访问异常: " + throwable.getMessage());
                        });
    }
}
